<template>
  <div class="app-container">
    <el-form :model="form" ref="form" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="收银员工号" prop="opid">
        <el-input v-model="form.opid" placeholder="请选择你的工号" clearable size="small" />
      </el-form-item>
      <el-form-item label="顾客编号" prop="cuid">
        <el-input v-model="form.cuid" placeholder="请输入顾客编号" clearable size="small" />
      </el-form-item>
      <el-form-item label="门店编号" prop="shopid">
        <el-input v-model="form.shopid" placeholder="请选择门店编号" clearable size="small" />
      </el-form-item>
      <el-button type="success" round @click="newOrder">新建订单</el-button>
    </el-form>

    <hr />
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="条形码" prop="barcode">
        <el-input
          v-model="queryParams.barcode"
          placeholder="请输入条形码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="条形码" align="center" prop="barcode" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column
        label="颜色"
        align="center"
        prop="coid"
        :formatter="((row,column)=>{return gDatasFormatter(row,column,colorList)})"
      />
      <el-table-column
        label="尺码"
        align="center"
        prop="size"
        :formatter="((row,column)=>{return gDatasFormatter(row,column,sizeList)})"
      />
      <el-table-column label="售价" align="center" prop="salePrice" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-plus" @click="addItems(scope.row)">添加</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pos:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <h3>订单明细：</h3>
    <el-table v-loading="loading" :data="itemsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="条形码" align="center" prop="barcode" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column
        label="颜色"
        align="center"
        prop="coid"
        :formatter="((row,column)=>{return gDatasFormatter(row,column,colorList)})"
      />
      <el-table-column
        label="尺码"
        align="center"
        prop="size"
        :formatter="((row,column)=>{return gDatasFormatter(row,column,sizeList)})"
      />
      <el-table-column label="数量" align="center">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.num"
            :min="1"
            size="mini"
            @change="scope.row.itemPrice=handleChange(scope.row.num,scope.row.salePrice,scope.row.itemPrice)"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" prop="salePrice" />
      <el-table-column label="小计" align="center" prop="itemPrice">
        <template slot-scope="scope">{{scope.row.itemPrice}}</template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pos:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="total_price">
      <h3>总计：{{totalPrice}}</h3>
    </div>
    <div class="btn_pay">
      <el-button type="success" round @click="submitOrder()">确认支付</el-button>
    </div>

    <el-dialog title="交易信息" :visible.sync="dialogFormVisible">
      <el-form :model="dialogForm">
        <el-form-item label="商品总金额：" :label-width="formLabelWidth">{{dialogForm.totalPrice}}</el-form-item>
        <el-form-item label="会员折扣：" :label-width="formLabelWidth">{{dialogForm.discount}}</el-form-item>
        <el-form-item label="应收：" :label-width="formLabelWidth">{{dialogForm.receivableAmount}}</el-form-item>
        <el-form-item label="支付方式：" :label-width="formLabelWidth">
          <el-select v-model="dialogForm.payway" placeholder="请选择支付方式">
            <el-option v-for="item in paywayList" :key="item.id" :label="item.way" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实收：" :label-width="formLabelWidth">
          <el-col :span="9">
            <el-input v-model="dialogForm.paidAmount" autocomplete="off"></el-input>
          </el-col>
          <el-button type="success" round @click="getChange()" class="changeBtn">计算找零</el-button>
        </el-form-item>
        <el-form-item label="找零：" :label-width="formLabelWidth">{{dialogForm.change}}</el-form-item>
        <el-form-item label="交易时间：" :label-width="formLabelWidth">{{dialogForm.time}}</el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="newPayment()">确 定</el-button>
      </div>
    </el-dialog>

   
  </div>
</template>

<script>
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  exportGoods
} from "@/api/system/goods";
import { listColor, getColor } from "@/api/system/color";
import { listCategory } from "@/api/system/category";
import { listMaterial } from "@/api/system/material";
import { addOrder, payOrder,exchangeOrderId } from "@/api/system/order";
import { getCustomer } from "@/api/system/customer";
import { getLevel } from "@/api/system/level";
import { addPayment } from "@/api/system/payment";

export default {
  name: "Goods",
  components: {},
  data() {
    return {
      //数量的默认值
      num: 1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedOrderItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // goods表格数据
      itemPrices: [],
      totalPrice: null,
      oid: null, //订单的id
      goodsList: [],
      // item表格数据
      itemsList: [],
      //传送到后台的order数据
      orderList: [[]],
      // 弹出层标题
      title: "商品",
      // 是否显示弹出层
      open: false,
      //小计价格
      itemPrice: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        barcode: null,
        cid: null,
        mid: null,
        coid: null,
        size: null,
        type: null,
        salePrice: null,
        inPrice: null,
        state: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      colorList: [],
      categoryList: [],
      materialList: [],
      colorName: null,
      typeList: [
        {
          id: 1,
          name: "上架"
        },
        {
          id: 2,
          name: "下架"
        }
      ],
      sizeList: [
        {
          id: 1,
          name: "S"
        },
        {
          id: 2,
          name: "M"
        },
        {
          id: 3,
          name: "L"
        },
        {
          id: 4,
          name: "XL"
        }
      ],
      dialogTableVisible: false,
      dialogFormVisible: false,
      dialogForm: {
        time: "",
        totalPrice: "",
        discount: 0,
        receivableAmount: "", //应收
        payway: "",
        paidAmount: "", //实收
        change: ""
      },
      paywayList: [
        {
          id: "0",
          way: "现金支付"
        },
        {
          id: "2",
          way: "微信支付"
        },
        {
          id: "1",
          way: "支付宝支付"
        },
        {
          id: "3",
          way: "银行卡支付"
        }
      ],
      formLabelWidth: "120px",
      level_id: "", //会员的等级
      paymentForm:{
        amount: null,
        payType: null,
        orderCode: null,
        actualMoney: null,
        discount: null
      }
    };
  },
  created() {
    this.getList();
    this.getColors();
    this.getCategory();
    this.getMaterial();
  },
  methods: {
    getColors() {
      listColor(this.queryParams).then(response => {
        this.colorList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.colorList);
      });
    },
    getCategory() {
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getMaterial() {
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询goods列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    gDatasFormatter(row, column, dicData) {
      let results = row[column.property]; // 默认原真实值
      if (dicData && dicData.length > 0) {
        for (let i = 0; i < dicData.length; i++) {
          let item = dicData[i];
          if (row[column.property] === item.id) {
            results = item.name;
            break;
          }
        }
      }
      return results;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        barcode: null,
        cid: null,
        mid: null,
        coid: null,
        size: null,
        type: null,
        salePrice: null,
        inPrice: null,
        createTime: null,
        state: null,
        remark: null
      };
      this.orderItemList = [];
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.totalPrice = 0;
      this.ids = selection.map(item => item.id);
      this.itemPrices = selection.map(item => item.itemPrice);
      for (var i = 0; i < this.itemPrices.length; i++) {
        this.totalPrice += this.itemPrices[i];
      }
      console.log(this.totalPrice);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加goods";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getGoods(id).then(response => {
        this.form = response.data;
        this.orderItemList = response.data.orderItemList;
        this.open = true;
        this.title = "修改goods";
      });
    },
    addItems() {
      if (this.goodsList != null) {
        console.log(this.goodsList);
        this.goodsList.map((item, index) => {
          this.itemsList.push(Object.assign(item, { itemPrice: "0" }));
        });
        //this.itemsList.push(this.goodsList[0])
        console.log(this.itemsList);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.orderItemList = this.orderItemList;
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //添加订单
    newOrder() {
      let that = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          addOrder(this.form).then(response => {
            this.msgSuccess("新增成功");
            this.open = false;
            this.getList();
            this.oid = response.data;
            console.log(this.oid)
             exchangeOrderId(this.oid).then(response=>{
               this.paymentForm.orderCode=response.msg
          });
          });
         
          getCustomer(this.form.cuid).then(response => {
            console.log(response.data);
            that.level_id = response.data.level;
            getLevel(that.level_id).then(response => {
              console.log(response.data.discount);
              that.dialogForm.discount = response.data.discount;
              console.log(that.dialogForm.discount);
            });
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除goods编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      });
      this.itemsList.splice(row - 1, 1);
    },
    /** item序号 */
    rowOrderItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** item添加按钮操作 */
    handleAddOrderItem() {
      let obj = {};
      obj.oid = "";
      obj.number = "";
      obj.salePrice = "";
      obj.subTotal = "";
      this.orderItemList.push(obj);
    },
    /** item删除按钮操作 */
    handleDeleteOrderItem() {
      if (this.itemsList.length == 0) {
        this.$alert("请先选择要删除的item数据", "提示", {
          confirmButtonText: "确定"
        });
      } else {
        this.itemsList.splice(this.itemsList[0].index - 1, 1);
      }
    },
    /** 单选框选中数据 */
    handleOrderItemSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.orderItem.clearSelection();
        this.$refs.orderItem.toggleRowSelection(selection.pop());
      } else {
        this.checkedOrderItem = selection;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有goods数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportGoods(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    },
    //计算小计
    handleChange(count, salePrice, itemPrice) {
      return (itemPrice = count * salePrice);
    },
    //提交订单
    submitOrder() {
      this.dialogFormVisible = true;
      var time = new Date();
      this.dialogForm.time = time.toLocaleString("zh", { hour12: false });
      console.log(time.toLocaleString());
      this.dialogForm.totalPrice = this.totalPrice;
      this.dialogForm.receivableAmount =
        this.totalPrice * (1 - this.dialogForm.discount);
      this.orderList = new Array(this.itemsList.length);
      for (let i = 0; i < this.itemsList.length; i++) {
        this.orderList[i] = new Array(2);
        for (let j = 0; j < 2; j++) {
          this.orderList[i][0] = this.itemsList[i].id;
          this.orderList[i][1] = this.itemsList[i].num;
        }
      }
      console.log(this.orderList);
      if (this.oid != null) {
        payOrder(this.oid, this.orderList).then(response => {
          this.msgSuccess("新增订单明细成功");
          this.open = false;
        });
      } else {
        this.msgSuccess("您还未新建订单");
      }
    },
    getChange() {
      this.dialogForm.change =
        this.dialogForm.paidAmount - this.dialogForm.receivableAmount;
    },
    //提交交易信息
    newPayment() {
      this.dialogFormVisible = false;
      this.paymentForm.amount=this.totalPrice;
      this.paymentForm.payType=this.dialogForm.payway;
     this.paymentForm.actualMoney=this.dialogForm.paidAmount;
     this.paymentForm.discount=this.dialogForm.discount;
      console.log(JSON.stringify(this.paymentForm));
      addPayment(JSON.stringify(this.paymentForm)).then(response => {
        this.msgSuccess("交易成功");
        this.open = false;
      });
    }
  }
};
</script>

<style>
.total_price {
  position: relative;
  left: 1200px;
}
.btn_pay {
  position: relative;
  left: 1200px;
}
</style>
